// pages/bus/bus.js

// const utils = require("../../workers/utils");

const worker = wx.createWorker('workers/index.js')

var config = wx.getStorageSync('config');


Page({
  /**
   * 页面的初始数据
   */
  data: {
    isRecord: false,
    isRecording: false,
    isRecordCancel: false,
    name: "",
    stations: [],
    busList: [],
    historyLines: [],
  },

  switchType: function () {
    console.log(this.data.isRecord)
    this.setData({
      "isRecord": !this.data.isRecord
    })
  },
  // 按下说话按键
  recordDown(e) {
    this.setData({
      "isRecordCancel": false,
      "isRecording": true,
      "moveStartY": e.changedTouches[0].clientY,
    })

    worker.onMessage((msg) => {
      let ret = JSON.stringify({
        data: {
          status: msg.isLastFrame ? 2 : 1, // 中间帧1， 最后一帧2
          format: 'audio/L16;rate=16000',
          encoding: 'mp3',
          audio: wx.arrayBufferToBase64(msg.frameBuffer),
        },
      })
      // console.log(ret)
      wss.send(ret)
    })

    const rm = wx.getRecorderManager();
    rm.onError((err) => {
      // 录音失败的回调处理
      console.log(err);
    });


    rm.onFrameRecorded(function (data) {
      // console.log(data)
      worker.postMessage(data)
    });

    rm.onStop((res) => {
      // 停止录音之后，把录取到的音频放在res.tempFilePath
      this.setData({
        src: res.tempFilePath
      })
      console.log(res.tempFilePath)

      let myaudio = wx.createInnerAudioContext(); // 创建audio对象
      myaudio.onError((res) => {
        // 播放音频失败的回调
        console.log(res)
      })
      myaudio.src = this.data.src; // 这里可以是录音的临时路径
      myaudio.play();

    });


    console.log("录音开始")
    const options = {
      duration: 10000, //录音的时长，单位 ms
      sampleRate: 44100, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 192000, //编码码率
      format: 'mp3', //音频格式
      frameSize: 1 //指定帧大小，单位 KB
    }
    rm.start(options)
  },
  // 松开说话按键
  recordUp() {
    this.setData({
      "isRecordCancel": false,
      "isRecording": false
    })
    console.log(this.data.moveStartY + "," + this.data.moveEndY)
    const rm = wx.getRecorderManager();

    rm.stop()

  },
  // 按下移动
  recordMove(e) {
    var y = e.changedTouches[0].clientY;

    var isRecordCancel = false;
    if (this.data.moveStartY - y > this.data.moveStartY / 5) {
      isRecordCancel = true;
    }
    this.setData({
      "moveEndY": y,
      "isRecordCancel": isRecordCancel
    })
    // console.log(e.changedTouches[0].clientX + "," + e.changedTouches[0].clientY)
  },

  onSearch: function () {
    console.log(this.data.name)
    if (this.data.name == "") {
      return;
    }
    var that = this;
    wx.request({
      url: config.host + "mini/bus/search?name=" + this.data.name,
      success: function (res) {
        that.setData({
          "name": ""
        })
        if (res.statusCode != 200) {
          console.log(res)
          return;
        }
        var data = res.data;
        console.log(data);
        that.setData({
          "stations": data.stationList,
          "busList": data.busList
        })

        if (data.busCount + data.stationCount == 1) {
          if (data.busCount == 1) {
            wx.navigateTo({
              url: "/pages/bus/line/line?id=" + that.data.busList[0].id + "&name=" + that.data.busList[0].name
            })
          } else {
            wx.navigateTo({
              url: "/pages/bus/stations/stations?id=" + that.data.stations[0].id
            })
          }
        }
      },
      fail: function (err) {
        console.log(err)
      }
    })
  },

  toLine: function (e) {
    console.log(e)
    console.log(wx.getStorageSync("historyLines"))
    let historyLines = JSON.parse(wx.getStorageSync("historyLines"));

    var busId = e.currentTarget.dataset.busid;
    var busName = e.currentTarget.dataset.busname;

    historyLines.push({
      "id": busId,
      "name": busName
    })

    const arrayUnique = (arr, name) => {
      const hash = {};
      return arr.reduce((item, next) => {
        hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
        return item;
      }, []);
    };
    let lines = arrayUnique(historyLines, 'id');
    console.log(lines)
    this.setData({
      "historyLines": lines.reverse()
    })
    wx.setStorageSync('historyLines', JSON.stringify(lines.reverse()));

    wx.navigateTo({
      url: '/pages/bus/line/line?id=' + busId + "&name=" + busName,
    })
  },
  clearLineHistory: function () {
    wx.setStorageSync('historyLines', "[]");
    this.setData({
      "historyLines": []
    })
  },
  toStation: function (e) {
    console.log(e)
    var stationId = e.currentTarget.dataset.stationid;
    wx.navigateTo({
      url: '/pages/bus/stations/stations?id=' + stationId,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let historyLines = wx.getStorageSync("historyLines");
    if (historyLines == "") {
      historyLines = "[]";
      wx.setStorageSync('historyLines', historyLines);
    }

    this.setData({
      "historyLines": JSON.parse(historyLines).reverse()
    });
    // this.onSearch();  // 方便测试，加了自动查询
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})